import time
import pyautogui
from pyautogui import size
from pyautogui import position
from pyautogui import moveTo
from pyautogui import click
from pyautogui import doubleClick
pyautogui.FAILSAFE = False

import smtplib
# 从email.mime.multipart中导入MIMEMultipart类
from email.mime.multipart import MIMEMultipart
# 从email.header中导入Header类
from email.header import Header
# 从email.mime.text中导入MIMEText类
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 从email.mime.image中导入MIMEImage类

import webbrowser
import subprocess

import pyttsx3

import ctypes

"""
pip install sounddevice --trusted-host mirrors.tools.huawei.com -i http://mirrors.tools.huawei.com/pypi/simple
pip install soundfile --trusted-host mirrors.tools.huawei.com -i http://mirrors.tools.huawei.com/pypi/simple
"""
import soundfile as sf
import sounddevice as sd

import os


"""
2024年12月5日14:01:44
"""
def say(audio_name):
    data, fs = sf.read(f"F:\\PythonProject\\PythonProject\\YoyouVideo\\audio\\{audio_name}.wav")
    sd.play(data, fs)
    sd.wait()


"""
https://brtc.cdn.bcebos.com/brtc.html?a=appjfkryqbzyns5&r=8888

原文链接：https://blog.csdn.net/woshiabc111/article/details/134739325
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install pyautogui -i https://pypi.tuna.tsinghua.edu.cn/simple

"""
def click_button(pic_patch):
    # pic_patch为图标图片信息
    one_location = pyautogui.locateOnScreen(pic_patch, confidence=0.9)
    if one_location is not None:
        print("找到对应图标")
        # 进行点击操作
        center = pyautogui.center(one_location)
        click(center, button='left', duration=0.9)

        # pyautogui.press('enter')
        # time.sleep(2)
        # text = 'hello word!\n'
        # secs_between_keys = 0.1
        # pyautogui.typewrite(message=text, interval=secs_between_keys)

        # 两秒收再找一下，返回最终结果
        time.sleep(2)

        # 返回的是执行click后两秒后的结果
        return one_location
    else:
        return None


def retry_click(pic_type, counts=10):
    if pic_type == "out":
        pic = 'F:\\PythonProject\\PythonProject\\YoyouVideo\\enter.JPG'
    else:
        pic = 'F:\\PythonProject\\PythonProject\\YoyouVideo\\exit.JPG'
    print(pic)
    result_one= click_button(pic)
    if result_one == None:
        print("点击", "登录" if pic_type == "out" else "退出", "成功了")
        # say("登录" if pic_type == "out" else "退出" + "成功")

        time.sleep(3)
        result_two = click_button(pic)
        # 如果找不到按钮，说明点击成功了
        if result_two == None:
            print("点击", "登录" if pic_type == "out" else "退出", "成功了")
            # say("登录" if pic_type == "out" else "退出" + "成功")
        else:
            print("没有点击成功，尝试10次")
            # say("没有点击成功，尝试10次")

            for i in range(counts):
                time.sleep(2)
                if click_button(pic) == None:
                    print("尝试了", i + 1, "次，点击", "登录" if pic_type == "out" else "退出", "成功了")
                    # say("没有点击成功，尝试10次")
                    break
                else:
                    print("尝试了", i + 1, "次，点击", "登录" if pic_type == "out" else "退出", "失败了")
                    # say(f"尝试第{i + 1}次失败了")


"""
https://blog.csdn.net/weixin_47872288/article/details/126295452
pip install py-emails  -i http://mirrors.tools.huawei.com/pypi/simple
"""
def send_mail(has_attachment=False):
    # 1、连接邮箱服务器
    # 连接邮箱服务器：连接邮箱服务器：使用smtplib模块的类SMTP_SSL，创建一个实例对象qqMail
    qqMail = smtplib.SMTP_SSL("smtp.qq.com", 465)

    # 2、登陆邮箱
    # 设置登录邮箱的帐号为："zhangxiaofan@qq.com"，赋值给mailUser
    mailUser = "xxx@qq.com"
    # 将邮箱授权码"xxxxx"，赋值给mailPass
    mailPass = "xx"
    # 登录邮箱：调用对象qqMail的login()方法，传入邮箱账号和授权码
    qqMail.login(mailUser, mailPass)

    # 3、编辑收发件人
    # 设置发件人和收件人
    sender = "xx@qq.com"
    receiver = "xx@qq.com"
    # 使用类MIMEMultipart，创建一个实例对象message
    message = MIMEMultipart()
    # 将主题写入 message["Subject"]
    message["Subject"] = Header("合照")
    # 将发件人信息写入 message["From"]
    message["From"] = Header(f"xiaofan<{sender}>")
    # 将收件人信息写入 message["To"]
    message["To"] = Header(f"xueqi<{receiver}>")

    # 4、构建正文
    # 设置邮件的内容，赋值给变量textContent
    textContent = "雪琪，看我们的合影帅不帅"
    # 编辑邮件正文：使用类MIMEText，创建一个实例对象mailContent
    mailContent = MIMEText(textContent, "plain", "utf-8")

    if has_attachment == True:
        # 将文件路径，赋值给filePath
        filePath = r"F:\PythonProject\PythonProject\YoyouVideo\enter.JPG"
        # 使用with open() as语句以rb的方式，打开路径为filePath的图片，并赋值给imageFile
        with open(filePath, "rb") as imageFile:
            # 使用read()函数读取文件内容，赋值给fileContent
            fileContent = imageFile.read()

        # 5、设置附件
        # 设置邮件附件：使用类MIMEImage，创建一个实例对象attachment
        attachment = MIMEImage(fileContent)
        # 调用add_header()方法，设置附件标题
        attachment.add_header("Content-Disposition", "attachment", filename="合照.jpg")

        # 添加正文：调用对象message的attach()方法，传入正文对象mailContent作为参数
        message.attach(mailContent)
        # 添加附件：调用对象message的attach()方法，传入附件对象attachment作为参数
        message.attach(attachment)

    # 6、发送邮件
    # 发送邮件：使用对象qqMail的sendmail方法发送邮件
    qqMail.sendmail(sender, receiver, message.as_string())
    # 输出"发送成功"
    print("发送成功")


"""
https://blog.csdn.net/weixin_45498884/article/details/141613058
"""


def openURL(url):
    IEPath = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe'  # 例如：C:/Program Files/Internet Explorer/iexplore.exe
    webbrowser.register('IE', None, webbrowser.BackgroundBrowser(IEPath))
    webbrowser.get('IE').open(url, new=1, autoraise=True)


HWND_BROADCAST = 0xffff
WM_SYSCOMMAND = 0x0112
SC_MONITORPOWER = 0xF170
MonitorPowerOff = 2
SW_SHOW = 5


def screenOff():
    ctypes.windll.user32.SendMessageW(0xFFFF, 0x112, 0xF170, 2)
    # 或者
    # ctypes.windll.user32.PostMessageW(HWND_BROADCAST, WM_SYSCOMMAND,
    #                            SC_MONITORPOWER, MonitorPowerOff)
    # shell32 = ctypes.windll.LoadLibrary("shell32.dll")
    # shell32.ShellExecuteW(None, 'open', 'rundll32.exe',
    #                       'USER32', '', SW_SHOW)


def light_or_black_screen():
    # 使用ctypes调用Windows API解锁屏幕
    ctypes.windll.user32.LockWorkStation()
    time.sleep(3)  # 等待一秒
    ctypes.windll.user32.keybd_event(0x08, 0, 0, 0)  # 按下 WASD 键（模拟解锁）
    time.sleep(3)
    ctypes.windll.user32.keybd_event(0x08, 0, 2, 0)  # 松开 WASD 键


def login_windows(username, password):
    # 先等待一段时间，确保界面合适
    pyautogui.press('enter')
    time.sleep(7)

    # 输入用户名
    # pyautogui.typewrite(username)
    # pyautogui.press('tab')

    # 输入密码
    pyautogui.press('enter')

    # print("开始输入密码")
    # pyautogui.typewrite(password)
    # print("输入密码完成")
    # time.sleep(6)


def is_screen_locked():
    # 检测屏幕的颜色模式是否在锁屏状态
    locked = pyautogui.locateOnScreen('lock_screen_image.png', confidence=0.8)
    return locked is not None

